/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) 2010 Roman Divotkey

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.demo.state;

import org.cogaen.box2d.PhysicsService;
import org.cogaen.core.Core;
import org.cogaen.demo.entity.HierarchicalEntity;
import org.cogaen.demo.entity.SquareEntity;
import org.cogaen.demo.view.PhysicsDemoView;
import org.cogaen.entity.EntityManager;
import org.cogaen.event.Event;
import org.cogaen.event.EventListener;
import org.cogaen.event.EventManager;
import org.cogaen.event.EventType;
import org.cogaen.resource.ResourceManager;
import org.cogaen.state.GameState;
import org.jbox2d.collision.PolygonDef;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;

public class PhysicsDemoState implements GameState, EventListener {
	
	/** Unique name of this state. */
	public static final String NAME = "Physics Demo";
	
	/** Width of game world in meters. */
	public static final double WORLD_WIDTH = 45.0;
	
	/** Indicates the end of this state. */
	public static final EventType END_OF_PHYSICS = new EventType("EndOfPhysics");
	
	/** Name of resource group associated with this state. */
	private static final String RES_GROUP = NAME;
	
	/** Default number of randomly placed objects. */
	private static final int DEFAULT_NUM_OF_OBJECTS = 9;
	
	/** Initial gravity to be set. */
	private static final Vec2 DEFAULT_GRAVITY = new Vec2(0.0f, -9.81f);
	
	private Core core;
	private PhysicsDemoView view;
	private Body walls[] = new Body[4];
	private int numOfObjects;
	
	public PhysicsDemoState(Core core, int numOfObjects) {
		this.core = core;
		this.numOfObjects = numOfObjects;
		this.view = new PhysicsDemoView(core);
		this.view.registerResources(RES_GROUP);
	}
	
	public PhysicsDemoState(Core core) {
		this(core, DEFAULT_NUM_OF_OBJECTS);
	}
	
	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public void onEnter() {
		// set physics engine to default gravity
		PhysicsService.getInstance( this.core ).setGravity( DEFAULT_GRAVITY );
		
		// load resource group
		ResourceManager.getInstance(this.core).loadGroup(RES_GROUP);
				
		// register for ChangeGravity event.
		EventManager.getInstance( this.core ).addListener(this, ChangeGravityEvent.TYPE );
		
		// initialize view
		this.view.engage();		
				
		// create level
		initLevel();
	}
	
	@Override
	public void onExit() {
		// destroy all level elements
		cleanUpLevel();
		
		// clean up view
		this.view.disengage();
		
		// unregister for events
		EventManager.getInstance(this.core).removeListener(this);
		
		// unload resource group associated with view/state
		ResourceManager.getInstance(this.core).unloadGroup(RES_GROUP);		
	}
	
	
	private void initLevel() {
		float width2 = (float) (WORLD_WIDTH * 0.5);
		float height2 = (float) (WORLD_WIDTH * this.view.getAspectRatio() * 0.5);
		World world = PhysicsService.getInstance( this.core ).getWorld();
		
		// create floor
		BodyDef def = new BodyDef();
		def.position.x = 0.0f;
		def.position.y = -height2 - 0.5f;
		this.walls[0] = world.createBody(def);
		
		PolygonDef polyDef = new PolygonDef();
		polyDef.setAsBox(width2, 0.5f);
		this.walls[0].createShape(polyDef);		
		
		// create ceiling
		def.position.x = 0.0f;
		def.position.y = height2 + 0.5f;
		this.walls[1] = world.createBody(def);;
		polyDef.setAsBox(width2, 0.5f);
		this.walls[1].createShape(polyDef);		
		
		// create left wall
		def.position.x = -width2 - 0.5f;
		def.position.y = 0.0f;
		this.walls[2] = world.createBody(def);;
		polyDef.setAsBox(0.5f, height2);
		this.walls[2].createShape(polyDef);		

		// create right wall
		def.position.x = width2 + 0.5f;
		def.position.y = 0.0f;
		this.walls[3] = world.createBody(def);;
		polyDef.setAsBox(0.5f, height2);
		this.walls[3].createShape(polyDef);		
				
		// create some dynamic objects within scene
		HierarchicalEntity hierarchical = new HierarchicalEntity(this.core, 0, 10);
		EntityManager.getInstance(this.core).addEntity(hierarchical);
		
		double delta = 2.5;
		int cnt = this.numOfObjects;
		int objectsPerLine = 16;
		int rows = 1 + this.numOfObjects / objectsPerLine;
		
		for (int i = 0; i < rows; ++i) {
			double y = -delta * 0.5 * (rows - 1) + i * delta;
			createObjectsInLine(Math.min(cnt, objectsPerLine), delta, y);
			cnt -= objectsPerLine;			
		}		
	}
	
	private void createObjectsInLine(int numOfObjects, double deltaX, double posY) {
		EntityManager entMngr = EntityManager.getInstance( this.core );
		
		for (int i = 0; i < numOfObjects; ++i) {
			double x = -deltaX * 0.5 * (numOfObjects - 1) + i * deltaX;
			// when we have enough different entities we will create
			// three different kinds of entities here. 
			if (i%3 == 0) {
				entMngr.addEntity( new SquareEntity(this.core, x, posY) );			
			} else if (i%3 == 1){
				entMngr.addEntity( new SquareEntity(this.core, x, posY) );							
			} else {
				entMngr.addEntity( new SquareEntity(this.core, x, posY) );			
			}
		}		
	}
	
	private void cleanUpLevel() {
		World world = PhysicsService.getInstance( this.core ).getWorld();
		
		for (int i = 0; i < this.walls.length; ++i) {
			if (this.walls[i] != null) {
				world.destroyBody( this.walls[i] );
				this.walls[i] = null;
			}
		}
		
		EntityManager.getInstance( this.core ).removeAllEntities();
	}

	@Override
	public void handleEvent(Event event) {
		if (event.getType().equals( ChangeGravityEvent.TYPE)) {
			ChangeGravityEvent changeGravity = (ChangeGravityEvent) event;
			PhysicsService.getInstance( this.core ).setGravity( changeGravity.getGravity() );
		}
	}

	public static class ChangeGravityEvent extends Event {

		public static final EventType TYPE = new EventType("ChangeGravity");
		private Vec2 gravity;
		
		public ChangeGravityEvent(double gx, double gy) {
			this.gravity = new Vec2((float) gx, (float) gy);
		}
		
		@Override
		public EventType getType() {
			return TYPE;
		}

		Vec2 getGravity() {
			return this.gravity;
		}
	}
	
}
